package com.huamoxi.controller;

import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.Random;

@RestController
public class PuzzleCaptchaController {
    private static final int WIDTH = 300; // 图片宽度
    private static final int HEIGHT = 150; // 图片高度
    private static final int TILE_WIDTH = 100; // 拼图块的宽度
    private static final int TILE_HEIGHT = 150; // 拼图块的高度

    @GetMapping("/puzzle")
    public void getPuzzle(HttpServletResponse response) throws Exception {
        BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
        Graphics g = image.getGraphics();

        // 设置背景色
        g.setColor(Color.LIGHT_GRAY);
        g.fillRect(0, 0, WIDTH, HEIGHT);

        // 随机生成拼图位置
        Random random = new Random();
        int xOffset = random.nextInt(WIDTH - TILE_WIDTH); // 横向偏移
        int yOffset = random.nextInt(HEIGHT); // 纵向偏移

        // 绘制拼图块
        g.setColor(Color.BLUE);
        g.fillRect(xOffset, yOffset, TILE_WIDTH, TILE_HEIGHT); // 绘制拼图蓝色块

        // 释放资源
        g.dispose();

        // 返回生成的图片
        response.setContentType("image/png");
        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(image, "png", out);
        out.flush();
    }
}
